package com.example.countscore;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class MyTask_BOC implements Runnable{

    private static final String TAG = "MyTask_BOC";

    private Handler handler;


    public void setHandler(Handler handler) {
        this.handler = handler;
    }

//    我的run方法
    public void run(){

        List<String> list_rate = new ArrayList<String>();
        //自定义列表数据
//        ArrayList<HashMap<String, String>> listItems = new ArrayList<HashMap<String, String>>();
        ArrayList<Item> listItems = new ArrayList<>();

        //使用Jsoup
        try {
            Document doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/").get();
            //第二个table为所需表
            Elements tables = doc.getElementsByTag("table");
            Element secondTable = tables.get(1);
            Elements trs = secondTable.getElementsByTag("tr");
            trs.remove(0); //删除表头
            Log.i(TAG, "run: trs--"+trs);

            for(Element tr:trs){
                Elements tds = tr.getElementsByTag("td");
                Element td1 = tds.get(0);
                Element td2 = tds.get(5);
                Log.i(TAG, "run: td2="+td2.text());

                float rate = 100f / Float.parseFloat(td2.text());

                //列表数据——msg
                list_rate.add(td1.text()+"----->"+rate);
                Log.i(TAG, "runList: "+td1.text()+"----->"+rate);

                //自定义列表数据——msg2
//                HashMap<String, String> map = new HashMap<String, String>();
//                map.put("ItemTitle", td1.text());
//                map.put("ItemDetail", String.valueOf(rate));
//                listItems.add(map);

                //使用item对象
                Item item = new Item(td1.text(), String.valueOf(rate));
                listItems.add(item);

            }
            //发送消息
            Message msg = handler.obtainMessage(8, list_rate);
            handler.sendMessage(msg);
            Log.i(TAG, "run: 消息已发送---BOC");

            //发送消息
            Message msg2 = handler.obtainMessage(9, listItems);
            handler.sendMessage(msg2);
            Log.i(TAG, "run: 消息已发送---BOC---自定义列表");
            Log.i(TAG, "run: listItems---"+listItems);


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
